package cn.glc.daily.life.common.auth;

import cn.glc.daily.life.common.constans.Constant;
import cn.glc.daily.life.common.exceptions.GlobalException;
import cn.glc.daily.life.common.utils.JwtUtils;
import cn.glc.daily.life.model.vo.jwt.auth.JwtUserDetailVo;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

import static cn.glc.daily.life.common.enums.GlobalCodeEnum.JwtBusinessExceptionEnum.USER_NOT_EXIST;

/**
 * @author simon
 * @date 2021/5/13 11:34
 * @copyright:
 * @modifier
 * @motto a no talent, people who have to study hard
 */
public abstract class AbstractUserHelper {

    /**
     * 获取当前登录人信息
     *
     * @return
     */
    protected static JwtUserDetailVo getUserInfo() {
        HttpServletRequest httpServletRequest = getCurrentHttpServletRequest();
        String userToken = httpServletRequest.getHeader(Constant.TOKEN_HEADER_NAME);
        Optional.ofNullable(userToken).orElseThrow(() -> new GlobalException(USER_NOT_EXIST));
        return JwtUtils.getUserInfo(userToken);
    }

    protected static HttpServletRequest getCurrentHttpServletRequest() {
        try {
            RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            if (requestAttributes instanceof ServletRequestAttributes) {
                return ((ServletRequestAttributes) requestAttributes).getRequest();
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }
}
